/*
 *    Copyright (c) 2018-2025, proj All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the proj developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: proj
 */

package com.ykht.proj.coupon.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ykht.proj.admin.api.feign.RemoteSysLogService;
import com.ykht.proj.common.core.util.R;
import com.ykht.proj.common.log.annotation.SysLog;
import com.ykht.proj.common.security.service.ProjUser;
import com.ykht.proj.common.security.util.SecurityUtils;
import com.ykht.proj.coupon.Enum.UserTypeEnum;
import com.ykht.proj.coupon.entity.CnCoupon;
import com.ykht.proj.coupon.entity.CnShop;
import com.ykht.proj.coupon.service.CnBrandService;
import com.ykht.proj.coupon.service.CnCompanyService;
import com.ykht.proj.coupon.service.CnCouponService;
import com.ykht.proj.coupon.service.CnShopService;
import com.ykht.proj.coupon.vo.CnCouponVo;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.List;


/**
 * 优惠券表
 *
 * @author proj code generator
 * @date 2020-11-16 17:00:20
 */
@RestController
@AllArgsConstructor
@RequestMapping("/cncoupon")
@Api(value = "cncoupon", tags = "优惠券表管理")
public class CnCouponController {

	private final CnCouponService cnCouponService;

	private final CnCompanyService cnCompanyService;

	private final CnBrandService cnBrandService;

	private final CnShopService cnShopService;

	private final RemoteSysLogService remoteSysLogService;

	/**
	 * 分页查询
	 *
	 * @param page       分页对象
	 * @param cnCouponVo 优惠券表
	 * @return
	 */
	@ApiOperation(value = "分页查询", notes = "分页查询")
	@GetMapping("/page")
	@PreAuthorize("@pms.hasPermission('coupon_cncoupon_view')")
	public R getCnCouponPage(Page page, CnCouponVo cnCouponVo) {
		Integer userType = SecurityUtils.getUser().getUserType();
		Long sjId = SecurityUtils.getSjId();
		if (userType.equals(UserTypeEnum.company.getValue())) {
			cnCouponVo.setCompanyId(sjId);
		}
		if (userType.equals(UserTypeEnum.brand.getValue())) {
			cnCouponVo.setBrandIds(sjId.toString());
		}
		if (userType.equals(UserTypeEnum.shop.getValue())) {
			CnShop cnShop = cnShopService.getById(sjId);
			cnCouponVo.setShopId(cnShop.getId());
			cnCouponVo.setBrandId(cnShop.getBrandId());
		}
		return cnCouponService.findPage(page, cnCouponVo);
	}


	/**
	 * 通过id查询优惠券表
	 *
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "通过id查询", notes = "通过id查询")
	@GetMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('coupon_cncoupon_view')")
	public R getById(@PathVariable("id") Long id) {
		return R.ok(cnCouponService.getById(id));
	}

	/**
	 * 新增优惠券表
	 *
	 * @param cnCouponVo 优惠券表
	 * @return R
	 */
	@ApiOperation(value = "新增优惠券表", notes = "新增优惠券表")
	@SysLog("新增优惠券表")
	@PostMapping
	@PreAuthorize("@pms.hasPermission('coupon_cncoupon_add')")
	public R save(@RequestBody CnCouponVo cnCouponVo) {

		if (cnCouponVo.getLowMoney() != null && cnCouponVo.getReductionMoney() != null
				&& cnCouponVo.getCouponType().equals(1)) {
			if (cnCouponVo.getLowMoney().compareTo(cnCouponVo.getReductionMoney()) == -1) {
				return R.failed("减免金额不能大于最低消费金额");
			}
		}
		List<String> dateList = cnCouponVo.getDateList();
		if (dateList != null && dateList.size() > 0) {
			final DateTimeFormatter formatter = new DateTimeFormatterBuilder()
					.appendPattern("yyyy-MM-dd[['T'hh][:mm][:ss]]")
					.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
					.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
					.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
					.parseDefaulting(ChronoField.MILLI_OF_SECOND, 0)
					.toFormatter();
			cnCouponVo.setEffectiveeStaTime(LocalDateTime.parse(dateList.get(0), formatter));
			cnCouponVo.setEffectiveeEndTime(LocalDateTime.parse(dateList.get(1), formatter));

			if (cnCouponVo.getEffectiveeEndTime().isBefore(LocalDateTime.now())) {
				return R.failed("活动结束日期要大于当前日期");
			}
		}
		return cnCouponService.insertCnCoupon(cnCouponVo);
	}

/*	public static void main(String[] args) {
		String date = "2021-05-10";
		DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
		final DateTimeFormatter formatter = new DateTimeFormatterBuilder()
				.appendPattern("yyyy-MM-dd[['T'hh][:mm][:ss]]")
				.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
				.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
				.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
				.parseDefaulting(ChronoField.MILLI_OF_SECOND, 0)
				.toFormatter();


		DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		LocalDateTime ldt = LocalDateTime.parse(date, formatter);

		System.out.println("String类型的时间转成LocalDateTime：" + ldt);
	}*/


	/**
	 * 修改优惠券表
	 *
	 * @param cnCoupon 优惠券表
	 * @return R
	 */
	@ApiOperation(value = "修改优惠券表", notes = "修改优惠券表")
	@SysLog("修改优惠券表")
	@PutMapping
	@PreAuthorize("@pms.hasPermission('coupon_cncoupon_edit')")
	public R updateById(@RequestBody CnCoupon cnCoupon) {
		return R.ok(cnCouponService.updateById(cnCoupon));
	}

	/**
	 * 通过id删除优惠券表
	 *
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "通过id删除优惠券表", notes = "通过id删除优惠券表")
	@SysLog("通过id删除优惠券表")
	@DeleteMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('coupon_cncoupon_del')")
	public R removeById(@PathVariable Long id) {
		return R.ok(cnCouponService.removeById(id));
	}

	/**
	 * 上下架
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(value = "上下架")
	@GetMapping("upOrLow")
	public R upOrLow(Long id) {
		return cnCouponService.upOrLow(id);
	}

	/**
	 * 获取门店
	 */
	@ApiOperation(value = "获取门店")
	@GetMapping("getShop")
	public R getShop(Integer brandId) {
		return cnCouponService.getShop(brandId.longValue());
	}

	/**
	 * 获取品牌
	 *
	 * @return
	 */
	@ApiOperation(value = "获取品牌")
	@GetMapping("getBrand")
	public R getBrand() {
		return cnCouponService.getBrand();
	}

	/**
	 * 获取登录人
	 *
	 * @return
	 */
	@ApiOperation(value = "获取登录人信息")
	@GetMapping("getUser")
	public R getUser() {
		ProjUser user = SecurityUtils.getUser();
		user.setLoginCount(remoteSysLogService.getUserNameCount(SecurityUtils.getUser().getUsername()).getData());
		return R.ok(user);
	}

	@GetMapping("/getCouponByShopName")
	public R getCouponByShopName(CnCouponVo cnCouponVo) {
		return R.ok(cnCouponService.getCouponByShopName(cnCouponVo));
	}
}
